<?php

namespace App\Models;


use App\Models\Concerns\ScopeFilterable;
use App\Observers\Contract\ObserverCleanable;
use App\Services\Locale\AppLanguage;
use App\Services\Utils\OSSable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;

/**
 * Class SplashAdvert - 广告（首屏 / 插屏）
 *
 * @property Url|null $redirectable
 * @property AdvertDescription[]|Collection $advertDescriptions
 * @package App\Models
 */
class SplashAdvert extends Model implements ObserverCleanable
{
    use OSSable,
        ScopeFilterable;

    protected $table = 'splash_adverts';

    protected static $unguarded = true;

    protected $appends = ['content'];

    protected $hidden = ['content_key'];

    protected $dates = ['started_at', 'ended_at'];

    protected $casts = [
        'advert_type_id'  => 'int',
        'redirectable_id' => 'int',
        'play_second'     => 'int',
        'sort_order'      => 'int',
        'can_skip'        => 'int',
    ];
    protected $content_key_prefix = 'panx/advert/';

    public function contentKeyPrefix(): string
    {
        return $this->content_key_prefix;
    }

    /**
     * @return string|null
     *
     * @throws \OSS\Core\OssException
     */
    public function getContentAttribute(): ?string
    {
        return $this->attributeToStaticUrl('content_key');
    }

    /**
     * @param $data
     *
     * @return string|null
     *
     * @throws \Exception
     */
    public function setContentAttribute($data)
    {
        if (is_file($data)) {
            $new_avatar = $this->uploadPostFile($data, $this->content_key_prefix);
            $this->attributes['content_key'] = $new_avatar;
        } else if (is_string($data) && strlen($data)) {
            $this->attributes['content_key'] = $data;
        }
    }

    /**
     * @return array
     */
    public function keyCleanColumns(): array
    {
        return [ 'content_key' ];
    }

    /**
     * @used-by $redirectable
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function redirectable(): MorphTo
    {
        return $this->morphTo('redirectable');
    }

    /**
     * 对应请求的多语言描述
     *
     * @return hasOne
     */
    public function localeDescription(): hasOne
    {
        return $this->hasOne(AdvertDescription::class, 'splash_advert_id', 'id')
            ->where('language_id', AppLanguage::getLanguageIdFromAppLocale());
    }

    /**
     * @used-by $advertDescriptions
     *
     * 多语言描述
     *
     * @return hasMany
     */
    public function advertDescriptions(): hasMany
    {
        return $this->hasMany(AdvertDescription::class, 'splash_advert_id', 'id');
    }
}
